/**
* 显示消息提示框
* @param content 提示的标题
*/
export function toast(content) {
  uni.showToast({
    icon: 'none',
    title: content
  })
}

/**
* 显示模态弹窗
* @param content 提示的标题
*/
export function showConfirm(content) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: '提示',
      content: content,
      cancelText: '取消',
      confirmText: '确定',
      success: function(res) {
        resolve(res)
      }
    })
  })
}

/**
* 参数处理
* @param params 参数
*/
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    var part = encodeURIComponent(propName) + "="
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']'
            var subPart = encodeURIComponent(params) + "="
            result += subPart + encodeURIComponent(value[key]) + "&"
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&"
      }
    }
  }
  return result
}


/**
 * openUrl 通用打开页面
 * @param url   跳转地址
 * @param type  跳转类型
 * @param num  控制APP右上角直接回到首页按钮
 */
export function openUrl(url, type = 1, num) {
	if (!url) return;
	if (url.indexOf("http://") >= 0 || url.indexOf("https://") >= 0) {
		// #ifndef H5
		let link = "/pages/my/webview?url=";
		if (num == 1) {
			link = "/pages/my/webview?num=1&url=";
		}
		uni.navigateTo({
			url: link + encodeURIComponent(url),
		});
		// #endif
		// #ifdef H5
		window.open(url);
		// #endif
		return;
	}
	if (type === 1 || type === 4) {
		let tabPage = ["pages/index/tabbar", "pages/my/index"];
		for (let tabPageUrl of tabPage) {
			if (url.indexOf(tabPageUrl) >= 0) {
				type = 2;
				break;
			}
		}
	}
	if (type === 1) {
		uni.navigateTo({
			url
		});
	} else if (type === 2) {
		uni.switchTab({
			url
		});
	} else if (type === 3) {
		uni.reLaunch({
			url
		});
	} else if (type === 4) {
		uni.redirectTo({
			url
		});
	} else if (type === 99) {
		uni.showToast({
			title: url,
			icon: "none"
		});
	}
}
/**
 * 返回上一级
 */
export function backPage(callback) {
	let backUrl = "/pages/index/index"; // 如果没有上一级页面就返回指定页面
	if (callback) {
		if (typeof callback === "function") {
			callback();
			return;
		} else if (typeof callback === "string") {
			backUrl = callback;
		}
	}
	let pages = getCurrentPages();
	if (pages.length > 1) {
		uni.navigateBack()
	} else {
		openUrl(backUrl, 4);
	}
}

/**
 * showToast 提示信息
 * @param title   提示文字
 * @param icon  图标
 * @param duration  时间毫秒
 */
export function showToast(title, icon = "none", duration = 2500) {
	uni.showToast({
		title,
		icon,
		duration,
	});
}

/**
 * callPhone 拨打电话
 * @param phoneNumber  电话号码
 */
export function callPhone(phoneNumber) {
	uni.makePhoneCall({
		phoneNumber,
	});
}

/**
 * showModel 模态框
 * @param title  标题
 * @param content  内容
 * @param cb  回调函数，按了确认之后做什么
 */
export function showModel({
	title = '系统提示',
	content,
	showCancel
}, sureCallback, cancelCallback) {
	uni.showModal({
		title,
		content,
		showCancel,
		confirmColor: "#FF5000",
		cancelColor: "#8C8C8C",
		success: (res) => {
			if (res.confirm) {
				sureCallback && sureCallback();
			} else if (res.cancel) {
				cancelCallback && cancelCallback()
			}
		},
	});
}

/**
 * @param {string} tel 隐藏手机号中间4位
 */
export function formatTel(tel) {
	var reg = /^(\d{3})\d{4}(\d{4})$/;
	return tel && tel.replace(reg, "$1****$2");
}

/** 
 * @param {string} text 复制的内容  
 */
export const copy = (text) => {
	if (text == '' || text == null || text == undefined) {
		return ''
	}
	if (typeof text !== 'string') {
		text = text.toString()
	}
	uni.setClipboardData({
		data: text,
		success: (res) => {
			// storage.set('clipboardText',text)
		}
	})
}

/**
 * 获取页面参数 
 */
export const getUrlParams = (key) => {
	let reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
	let r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

/**
 * 上传图片
 * @parm {count: 数量} 
 */
export const chooseImgUpload = (count = 1) => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'], //从相册选择
			success(res) {
				uni.showLoading({
					title: '上传中...'
				})
				for (let i = 0; i < res.tempFilePaths.length; i++) {
					let tempFile = res.tempFilePaths[i]
					uploadFilePromise(tempFile).then(val => {
						resolve(val)
						uni.hideLoading()
					})
				}

			}
		})
	})
}

/**
 * 获取地址信息并筛选 
 */
export const filterAddress = (...args) => {
	return new Promise((resolve, reject) => {
		let filterObj = {}
		selectAddressByIdAPI().then(res => {
			if (args.length > 0) {
				for (let i in res.data) {
					if (args.includes(i)) {
						filterObj[i] = res.data[i]
					}
				}
			} else {
				filterObj = res.data
			}
			resolve(filterObj)
		}).catch(err => {
			reject(JSON.stringify(err))
		})
	})

}

//将网络图片转成本地图片
function getBase64Image(url) {
	var image = new Image()
	image.src = url + '&v=' + Math.random() // 处理缓存
	image.crossOrigin = '*' // 支持跨域图片
	image.onload = function() {
		$(".invit_info_qrcode").attr("src", drawBase64Image(image))
		convertDivToImage("my_div")
	}
}

//将图片转成base64，返回字符串
function drawBase64Image(img) {
	var canvas = document.createElement('canvas')
	canvas.width = img.width
	canvas.height = img.height
	var ctx = canvas.getContext('2d')
	ctx.drawImage(img, 0, 0, img.width, img.height)
	var dataURL = canvas.toDataURL('image/png')
	return dataURL
}

//转换图片，传入元素id
function convertDivToImage(divId) {
	const $element = $('#' + divId);
	$element.css('background-color', '#fff')
	html2canvas($element[0]).then((canvas) => {
		const imgData = canvas.toDataURL('image/png');
		const imgEle = $('#review').attr('src', imgData).attr('width', canvas.width).attr('height', canvas
			.height);
		$element.replaceWith(imgEle);
	});
}

const formatNumber = (n) => {
	n = n.toString();
	return n[1] ? n : `0${n}`;
};
// 生成随机事件戳
export const formatTime = (date, type) => {
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();

	switch (type) {
		case 'YY':
			return `${[year].map(formatNumber).join('-')}`;
		case 'MM':
			return `${[year, month].map(formatNumber).join('-')}`;
		case 'DD':
			return `${[year, month, day].map(formatNumber).join('-')}`;
		case 'HH':
			return `${[year, month, day].map(formatNumber).join('-')} ${[hour].map(formatNumber).join(':')}`;
		case 'mm':
			return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute].map(formatNumber).join(':')}`;
		case 'ss':
			return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`;
		case 'HHmmss':
			return `${[hour, minute, second].map(formatNumber).join(':')}`;
		case 'unix':
			const unix =
				`${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`;
			return Math.round(new Date(unix).getTime() / 1000);
		default:
			return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`;
	}
};

/**
 * 校验银行卡
 * @param bankno 银行卡号
 */
export function luhnCheck(bankno) {
	var lastNum = bankno.substr(bankno.length - 1, 1); //取出最后一位（与luhn进行比较）
	var first15Num = bankno.substr(0, bankno.length - 1); //前15或18位
	var newArr = new Array();
	for (var i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存进数组
		newArr.push(first15Num.substr(i, 1));
	}
	var arrJiShu = new Array(); //奇数位*2的积 <9
	var arrJiShu2 = new Array(); //奇数位*2的积 >9
	var arrOuShu = new Array(); //偶数位数组
	for (var j = 0; j < newArr.length; j++) {
		if ((j + 1) % 2 == 1) { //奇数位
			if (parseInt(newArr[j]) * 2 < 9) arrJiShu.push(parseInt(newArr[j]) * 2);
			else arrJiShu2.push(parseInt(newArr[j]) * 2);
		} else //偶数位
			arrOuShu.push(newArr[j]);
	}

	var jishu_child1 = new Array(); //奇数位*2 >9 的分割之后的数组个位数
	var jishu_child2 = new Array(); //奇数位*2 >9 的分割之后的数组十位数
	for (var h = 0; h < arrJiShu2.length; h++) {
		jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
		jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
	}

	var sumJiShu = 0; //奇数位*2 < 9 的数组之和
	var sumOuShu = 0; //偶数位数组之和
	var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
	var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
	var sumTotal = 0;
	for (var m = 0; m < arrJiShu.length; m++) {
		sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
	}

	for (var n = 0; n < arrOuShu.length; n++) {
		sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
	}

	for (var p = 0; p < jishu_child1.length; p++) {
		sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
		sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
	}
	//计算总和
	sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);

	//计算luhn值
	var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
	var luhn = 10 - k;

	if (lastNum == luhn) {
		return true;
	} else {
		return false;
	}
}

// 时间格式
export const formatTimeDays = (days = 5) => {
	let dateArr = []
	let today = new Date();
	let nowTime = today.getTime() // 当前时间戳
	// this.nowTimes = parseInt(nowTime / 1000)
	for (let i = 0; i < days; i++) {
		let newDate = new Date(today.getTime() + i * 1000 * 60 * 60 * 24)
		let month = (parseInt(newDate.getMonth()) + 1) > 9 ? (parseInt(newDate.getMonth()) + 1) : "0" + (parseInt(
			newDate.getMonth()) + 1) // 当前月份
		let day = (newDate.getDate()) > 9 ? newDate.getDate() : "0" + newDate.getDate() //当前日期
		let backTime = newDate.getTime() // 几天后时间戳
		let backDays = newDate.getDay() // 几天后周几
		let remTime = (backTime - nowTime) / 1000 // 距离今天几天
		let week = ''
		if (remTime == 0) {
			week = "今天"
		} else if (remTime == 86400) {
			week = "明天"
		} else if (remTime == 172800) {
			week = "后天"
		} else {
			if (backDays == 0) {
				week = "周日"
			} else if (backDays == 1) {
				week = "周一"
			} else if (backDays == 2) {
				week = "周二"
			} else if (backDays == 3) {
				week = "周三"
			} else if (backDays == 4) {
				week = "周四"
			} else if (backDays == 5) {
				week = "周五"
			} else if (backDays == 6) {
				week = "周六"
			}
		}
		let fullDate = `${month}-${day}`
		let ass = {
			weeks: week,
			days: fullDate
		}
		dateArr.push(ass)
	}
	return dateArr
}

/**
 *  过滤请求参数
 */
export function filterOptions(options) {
	let newOptions = {}
	for (let key in options) {
		if (options[key] == undefined) {
			continue;
		}
		newOptions[key] = options[key]
	}

	return newOptions
}